package org.realogic.btp.dhtmlx;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

public class DhtmlxHttpMessageConverter extends AbstractHttpMessageConverter<DhtmlxGridXml> {

	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

	@Override
	protected boolean supports(Class<?> clazz) {
		Class<?>[] theInterfaces = clazz.getInterfaces();
		for (int i = 0; i < theInterfaces.length; i++) {
			if (theInterfaces[i].getName().equalsIgnoreCase(DhtmlxGridXml.class.getName())) {
				return true;
			}
		}
		return true;
	}

	public DhtmlxHttpMessageConverter() {
		super(new MediaType("application", "xml", DEFAULT_CHARSET));
	}

	protected DhtmlxGridXml readInternal(Class<? extends DhtmlxGridXml> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
		return null;
	}

	protected void writeInternal(DhtmlxGridXml object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
		if (object != null) {
			OutputStream os = outputMessage.getBody();
			OutputStreamWriter writer = new OutputStreamWriter(os);
			object.toXml(writer);
		}
	}
}
